NOTE
5.1 Redis Key Expiration Strategy
Redis key expiration commands and passive and active expiration mechanisms.
This is a historical learning note and may contain outdated or incomplete understanding.
1. What Does Redis Key Expiration Mean?
It means when a key is actually deleted after an expiration time has been set. Expiration precision is 0–1 ms.
2. Redis Key Expiration Commands
expirecan set a timeout.- If the key exists, the reply is 1; if the key does not exist, it returns 0.
persistcan clear the timeout and make the key permanent.- After a key is renamed with
rename, the new key inherits the old key’s expiration.
3. How Redis Key Expiration Works
3.1. Passive Method: Lazy Deletion
- When a key is accessed, Redis checks whether it has expired and deletes it if so.
- Disadvantage: if an expired key is never accessed, it continues occupying memory, which is equivalent to a memory leak.
3.2. Active Method: Periodic Random Deletion
- Because iterating through all keys would create too much CPU load, Redis only randomly selects some keys for deletion.
- Redis performs the following operation 10 times per second:
- Randomly select 20 keys that have expiration times.
- Delete the expired keys.
- If more than 25% of the selected keys were deleted, repeat step 1.

Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub